/*
 * HibernateWorker.java
 *
 * Created on 24 December 2007, 08:56
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package my.com.sunway.util;

import my.com.sunway.event.HibernateEvent;
import my.com.sunway.listener.HibernateEventListener;
import net.sf.hibernate.*;
import org.apache.log4j.*;
import java.io.*;

/**
 *
 * @author ngcw
 */
public class HibernateWorker implements Runnable,Serializable{
 static final long serialVersionUID = 10275539472837495L;
 static Logger logger = Logger.getLogger(HibernateWorker.class);
    HibernateEventListener listener = null;
    ScrollableResults results = null;
    //Query query = null;
    int items_per_page = 10;
    String className = null;
    
    /** Creates a new instance of HibernateWorker */
    public HibernateWorker() {
    }
    
    public HibernateWorker(ScrollableResults results, int items_per_page, String className) {
        this.results = results;
        this.items_per_page = items_per_page;
        this.className = className;
    }
    
    public void addHibernateEventListener(HibernateEventListener listener){
        this.listener = listener;
    }
    
    public void setResults(ScrollableResults results){
        this.results = results;
    }
    
    public ScrollableResults getResults(){
        return results;
    }
    
    public void setItems_per_page(int items_per_page){
        this.items_per_page = items_per_page;
    }
    
    public int getItems_per_page(){
        return items_per_page;
    }
    
    public void setClassName(String className){
        this.className = className;
    }
    
    public String getClassName(){
        return className;
    }
    
    public void run(){
        boolean hasNext = true;
        Class clazz = null;
        
        try{
        //results = query.scroll();
        if(listener!=null && results!=null){
            results.first();
            for(int row=0; row<items_per_page && hasNext; row++){
                hasNext = results.next();
                Object obj = results.get(0);
                clazz = Class.forName(className);
                //if(obj instanceof Object){
                if(clazz.isInstance(obj)){
                    //logger.info("added row "+row);
                    listener.dataRowFetched(new HibernateEvent(obj));
                }else{
                  hasNext = false;                
                }
            }            
        }
        }catch(Exception ex){
          logger.error(ex.toString());
        }finally{
         listener.transactionCompleted(new HibernateEvent("completed"));
        }
    }
}
